package com.atao.baokede.service.serviceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.atao.baokede.constant.OrderConstant;
import com.atao.baokede.mapper.ItemOrderDetailMapper;
import com.atao.baokede.mapper.ItemOrderMapper;
import com.atao.baokede.pojo.Cart;
import com.atao.baokede.pojo.Item;
import com.atao.baokede.pojo.DetailOrder;
import com.atao.baokede.pojo.ItemOrder;
import com.atao.baokede.pojo.dto.DelayCartOrderDto;
import com.atao.baokede.pojo.vo.ItemOrderVo;
import com.atao.baokede.service.CartService;
import com.atao.baokede.service.ItemOrderService;
import com.atao.baokede.service.ItemService;
import com.atao.baokede.utils.OrderIdUtil;
import com.atao.baokede.utils.ThreadLocalUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.atao.baokede.constant.RabbitMqConstant.*;

@Service
public class ItemOrderServiceImpl implements ItemOrderService {
    @Autowired
    private ItemOrderMapper itemOrderMapper;
    @Autowired
    private ItemOrderDetailMapper itemOrderDetailMapper;
    @Autowired
    private ItemService itemService;
    @Autowired
    private CartService cartService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Override
    public void cancelOrder(Long orderId) {
        itemOrderMapper.cancelOrder(orderId);
    }

    @Override
    public ItemOrder selectByOrderNo(Long orderNo) {
        return itemOrderMapper.selectByOrderNo(orderNo);
    }

    @Override
    @Transactional
    public ItemOrderVo addOrder(Long itemId, Long num, Long addressId, String spec) {
        // 获取商品信息
        Item item = itemService.findById(itemId);
        String s = OrderIdUtil.generateOrderId();
        Long l = Long.valueOf(s);
        System.out.println(l);

        itemService.reduceStock(itemId, num);
        // 创建订单
        ItemOrder itemOrder = new ItemOrder();
        itemOrder.setOrderId(l);
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        itemOrder.setUserId(userId);
        BigDecimal decimal = BigDecimal.valueOf(num).multiply(item.getPrice());
        itemOrder.setAmount(decimal);
        itemOrder.setAddressId(addressId);
        itemOrder.setStatus(OrderConstant.STATUS_UNPAID);
        itemOrderMapper.addOrder(itemOrder);

        // 创建订单详情
        DetailOrder detailOrder = new DetailOrder();
        detailOrder.setOrderId(l);
        detailOrder.setItemId(itemId);
        detailOrder.setNum(num);
        detailOrder.setPrice(decimal);
        detailOrder.setSpec(spec);
        detailOrder.setMerchantId(item.getMerchantId());
        detailOrder.setItemName(item.getName());

        itemOrderDetailMapper.addOrderDetail(detailOrder);

        rabbitTemplate.convertAndSend(DELAY_EXCHANGE_NAME,
                DELAY_ROUTING_KEY,
                itemOrder.getOrderId(),
                msg -> {
                    msg.getMessageProperties().setHeader("x-delay", 900000);
                    return msg;
                });


        return new ItemOrderVo(l, decimal, LocalDateTime.now());
    }

    @Override
    public void modify(ItemOrder itemOrder) {
        itemOrderMapper.modify(itemOrder);
    }

    @Override
    @Transactional
    public ItemOrderVo addCartOrder(List<Long> ids, Long addressId) {
        // 获取购物车中的商品信息
        List<Cart> cartList = cartService.findByIds(ids);

        // 计算总金额
        BigDecimal total = BigDecimal.ZERO;
        for (Cart cart : cartList) {
            total = total.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNum())));
        }

        // 向商品订单表插入一条数据
        ItemOrder itemOrder = new ItemOrder();
        Long value = Long.valueOf(OrderIdUtil.generateOrderId());
        itemOrder.setOrderId(value);
        Map<String, Object> map = ThreadLocalUtil.get();
        Long userId = ((Number) map.get("id")).longValue();
        itemOrder.setUserId(userId);
        itemOrder.setAmount(total);
        itemOrder.setAddressId(addressId);
        itemOrder.setStatus(OrderConstant.STATUS_UNPAID);
        itemOrderMapper.addOrder(itemOrder);

        // 提取所有商品 ID
        List<Long> itemIds = cartList.stream()
                .map(Cart::getItemId)
                .distinct()
                .toList();
        // 批量查询商品信息
        List<Item> itemList = itemService.findItemsByIds(itemIds);

        // 构建商品 ID 到商家 ID 的映射
        Map<Long, Long> itemIdToMerchantIdMap = itemList.stream()
                .collect(Collectors.toMap(Item::getId, Item::getMerchantId));


        //向商品详细订单表插入n条数据
        List<DetailOrder> detailOrders = new ArrayList<>();
        for (Cart cart : cartList) {
            DetailOrder detailOrder = new DetailOrder();
            BeanUtil.copyProperties(cart, detailOrder);
            detailOrder.setOrderId(itemOrder.getOrderId());
            detailOrder.setItemName(cart.getName());
            // 从映射中获取商家 ID
            Long merchantId = itemIdToMerchantIdMap.get(cart.getItemId());
            if (merchantId != null) {
                detailOrder.setMerchantId(merchantId); // 设置商家 ID
            }
            detailOrders.add(detailOrder);
        }
        System.out.println("detailOrders:" + detailOrders.toString());
        itemOrderDetailMapper.addBatchOrderDetail(detailOrders);

        //批量扣减库存
        System.out.println(cartList);
        itemService.reduceStockBatch(cartList);

        // 删除购物车中的选中的商品（即ids中的商品)
        cartService.deleteByCartIds(ids);

        DelayCartOrderDto delayCartOrderDto = new DelayCartOrderDto();
        delayCartOrderDto.setIds(ids);
        delayCartOrderDto.setOrderId(itemOrder.getOrderId());

        rabbitTemplate.convertAndSend(DELAY_EXCHANGE_NAME,
                DELAY_ROUTING_KEY2,
                delayCartOrderDto,
                msg -> {
                    msg.getMessageProperties().setHeader("x-delay", 900000);
                    return msg;
                });

        return new ItemOrderVo(itemOrder.getOrderId(), itemOrder.getAmount(), LocalDateTime.now());
    }

    @Override
    public DetailOrder getItemDetail(Long orderId) {
        return itemOrderDetailMapper.getItemDetail(orderId);
    }

    @Override
    public void updateStatus(Long orderNo, int status) {
        itemOrderMapper.updateStatus(orderNo,status);
    }

}
